# gozerlib/wave/event.py
#
#

""" google wave events. """

## gozerlib imports
from gozerlib.utils.auth import finduser
from gozerlib.eventbase import EventBase

## basic imports

import logging
import cgi

class WaveEvent(EventBase):


    """ a wave event. """

    def __init__(self):
        EventBase.__init__(self)
        self.type = "wave"
        self.msg = False

    def parse(self, bot, properties, context):

        """ parse properties and context into a WaveEvent. """

        logging.debug("WaveEvent created: %s" % repr(properties))
        self.bot = bot
        self.properties = properties

        if self.properties.has_key('ispoller'):
            self.poller = True
        else:
            self.poller = False

        self.context = context
        logging.debug("context: %s" % dir(self.context))
        self.blipid = properties['blipId']
        self.blip = context.GetBlipById(self.blipid)
        if not self.blip:
            logging.warn("can't get blip id: %s" % self.blipid)
            self.contributors = []
            self.doc = None
            self.txt = ""
            self.userhost = ""
            self.poller = False
        else:
            logging.debug("blip: %s" % dir(self.blip))
            logging.debug("blip_ops_context: %s" % dir(self.blip._OpBasedBlip__context))
            self.contributors = list(self.blip.GetContributors())
            self.doc = self.blip.GetDocument()
            logging.debug("document: %s" % dir(self.doc))
            logging.debug("document data: %s" % str(self.doc))
            self.origtxt = self.doc.GetText()
            self.txt = self.origtxt.strip()
            self.userhost = self.blip.GetCreator()
            self.elements = self.blip.elements
            logging.debug("elements: %s" % str(self.elements))

            for nr, elem in self.elements.iteritems():
                if elem.get('ispoller') == 'yes':
                    self.poller = True
                              
        self.auth = self.userhost
        logging.debug("auth is %s" % self.auth)
        self.root = context.GetRootWavelet()
        logging.debug("root: %s" % dir(self.root))
        logging.debug("raw_data: %s" % str(self.root.raw_data))
        self.channel = self.root.waveId
        self.title = self.root.title or self.channel 
        self.waveid = self.channel
        self.url = "https://wave.google.com/wave/#restored:wave:%s" % self.waveid.replace('w+','w%252B')
        self.makeargs()        
        logging.warn(u'wave - in - %s - %s' % (self.userhost, self.txt))

    def __deepcopy__(self, a):

        """ deepcopy a wave event. """

        e = WaveEvent()
        e.copyin(self)
        return e

    def _raw(self, outtxt, root=None):

        """ send raw text to the server .. creates a blip on the root. """
        outtxt = unicode(outtxt)

        if root:
            blip = root.CreateBlip()
        else:
            blip = self.root.CreateBlip()

        logging.warn(u"wave - out - %s - %s" % (self.userhost, outtxt))
        blip.GetDocument().AppendText(outtxt)

    def reply(self, txt, resultlist=[], nritems=False, *args, **kwargs):

        """ reply to blip. """

        if self.checkqueues(resultlist):
            return

        outtxt = self.makeresponse(txt, resultlist, nritems, *args, **kwargs)

        if not outtxt:
            return

        #self.doc.SetText(cgi.escape(outtxt))
        (res1, res2) = self.less(outtxt)
        self.write(res1)
        if res2:
            self.write(res2)

    def write(self, outtxt):

        """ write outtxt to the server. """
        outttxt = unicode(outtxt)
        logging.warn(u"wave - out - %s - %s" %  (self.userhost, outtxt))

        if not self.child:
            self.child = self.blip.CreateChild()
            #logging.debug("child: %s" % dir(self.child))

        if self.replied:
            self.child.GetDocument().AppendText("\n\n")

        self.child.GetDocument().AppendText(outtxt)
        self.replied = True

    def write_root(self, outtxt, root=None):

        """ write to the root of a wave. """

        self._raw(outtxt, root)

    def replyroot(self, txt, resultlist=[], nritems=False, root=None, *args, **kwargs):

        """ reply to wave root. """

        if self.checkqueues(resultlist):
            return

        if resultlist:
            outtxt = txt + u" " + u' .. '.join(resultlist)
        else:
            outtxt = txt

        if not outtxt:
            return
        logging.debug("wave - reply root: %s - %s" % (self.root, root))
        (res1, res2) = self.less(outtxt)
        self.write_root(res1, root)
        if res2:
            self.write_root(res2, root)
